{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import matplotlib as mpl\n",
    "import numpy as np\n",
    "import sklearn\n",
    "import sys\n",
    "import os\n",
    "import pandas as pd\n",
    "import tensorflow as tf\n",
    "from tensorflow.python import keras\n",
    "\n",
    "loss_train_list=[]\n",
    "loss_test_list=[]\n",
    "acc_train_list=[]\n",
    "acc_test_list=[]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 2471 images belonging to 2 classes.\n",
      "Found 152 images belonging to 2 classes.\n",
      "2471 152\n"
     ]
    }
   ],
   "source": [
    "root_directory = \"../dataset/data4/\"\n",
    "train_directory = \"train\"\n",
    "val_directory = \"val\"\n",
    "height = 40\n",
    "width = 40\n",
    "channels = 3\n",
    "batch_size = 32\n",
    "num_classes = 2\n",
    "# 数据增强\n",
    "\n",
    "train_datagen = keras.preprocessing.image.ImageDataGenerator(\n",
    "    rescale=1. / 255,\n",
    "    rotation_range=10,  # 旋转40度\n",
    "    width_shift_range=0.2,  # 位移 0.2 个比例 20% 平移\n",
    "    height_shift_range=0.2,  #\n",
    "    shear_range=0.3,  # 增强强度\n",
    "    zoom_range=0.2,\n",
    "    horizontal_flip=True,\n",
    "    fill_mode='nearest',  # 填充\n",
    ")\n",
    "train_generator = train_datagen.flow_from_directory(root_directory + train_directory,\n",
    "                                                    target_size=(height, width),\n",
    "                                                    batch_size=batch_size,\n",
    "                                                    seed=7,\n",
    "                                                    shuffle=True,\n",
    "                                                    class_mode=\"categorical\")\n",
    "validation_datagen = keras.preprocessing.image.ImageDataGenerator(\n",
    "    rescale=1. / 255,\n",
    "    width_shift_range=0.2,  # 位移 0.2 个比例 20% 平移\n",
    "    height_shift_range=0.2,  #\n",
    "    shear_range=0.3,  # 增强强度\n",
    "    zoom_range=0.2,\n",
    "    horizontal_flip=True,\n",
    "    fill_mode='nearest',  # 填充\n",
    ")\n",
    "validation_generator = validation_datagen.flow_from_directory(root_directory + val_directory,\n",
    "                                                              target_size=(height, width),\n",
    "                                                              batch_size=batch_size,\n",
    "                                                              seed=7,\n",
    "                                                              shuffle=False,\n",
    "                                                              class_mode=\"categorical\")\n",
    "train_num = train_generator.samples\n",
    "valid_num = validation_generator.samples\n",
    "print(train_num, valid_num)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"sequential\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "conv2d (Conv2D)              (None, 40, 40, 32)        896       \n",
      "_________________________________________________________________\n",
      "conv2d_1 (Conv2D)            (None, 40, 40, 32)        9248      \n",
      "_________________________________________________________________\n",
      "max_pooling2d (MaxPooling2D) (None, 20, 20, 32)        0         \n",
      "_________________________________________________________________\n",
      "conv2d_2 (Conv2D)            (None, 20, 20, 64)        18496     \n",
      "_________________________________________________________________\n",
      "conv2d_3 (Conv2D)            (None, 20, 20, 64)        36928     \n",
      "_________________________________________________________________\n",
      "max_pooling2d_1 (MaxPooling2 (None, 10, 10, 64)        0         \n",
      "_________________________________________________________________\n",
      "conv2d_4 (Conv2D)            (None, 10, 10, 64)        36928     \n",
      "_________________________________________________________________\n",
      "conv2d_5 (Conv2D)            (None, 10, 10, 64)        36928     \n",
      "_________________________________________________________________\n",
      "max_pooling2d_2 (MaxPooling2 (None, 5, 5, 64)          0         \n",
      "_________________________________________________________________\n",
      "flatten (Flatten)            (None, 1600)              0         \n",
      "_________________________________________________________________\n",
      "dense (Dense)                (None, 64)                102464    \n",
      "_________________________________________________________________\n",
      "dense_1 (Dense)              (None, 2)                 130       \n",
      "=================================================================\n",
      "Total params: 242,018\n",
      "Trainable params: 242,018\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "# 3、开始建立模型\n",
    "model = keras.models.Sequential([\n",
    "    keras.layers.Conv2D(filters=32, kernel_size=3, padding='same',\n",
    "                        activation='relu', input_shape=[width, height, channels]),\n",
    "    keras.layers.Conv2D(filters=32, kernel_size=3, padding='same',\n",
    "                        activation='relu'),\n",
    "    keras.layers.MaxPool2D(pool_size=2),\n",
    "\n",
    "    keras.layers.Conv2D(filters=64, kernel_size=3, padding='same',\n",
    "                        activation='relu'),\n",
    "    keras.layers.Conv2D(filters=64, kernel_size=3, padding='same',\n",
    "                        activation='relu'),\n",
    "    keras.layers.MaxPool2D(pool_size=2),\n",
    "\n",
    "    keras.layers.Conv2D(filters=64, kernel_size=3, padding='same',\n",
    "                        activation='relu'),\n",
    "    keras.layers.Conv2D(filters=64, kernel_size=3, padding='same',\n",
    "                        activation='relu'),\n",
    "    keras.layers.MaxPool2D(pool_size=2),\n",
    "    keras.layers.Flatten(),\n",
    "    keras.layers.Dense(64, activation='relu'),\n",
    "    keras.layers.Dense(num_classes, activation='softmax')\n",
    "])\n",
    "print(model.summary())"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "outputs": [],
   "source": [
    "model.compile(loss='categorical_crossentropy',\n",
    "              optimizer='adam', metrics=['accuracy'])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "for i in range(6):\n",
    "    epochs = 1\n",
    "    # model.load_weights('./model/gaijin2_save_weights')\n",
    "    history = model.fit_generator(train_generator,\n",
    "                              steps_per_epoch=train_num // batch_size,\n",
    "                              epochs=epochs,\n",
    "                              validation_data=validation_generator,\n",
    "                              validation_steps=valid_num, verbose=2)\n",
    "    model.save_weights('./model/gaijin2_save_weights_ls',save_format='tf')\n",
    "    # data = {}\n",
    "    # label = 'accuracy'\n",
    "    # data[label] = history.history[label]\n",
    "    # data['val' + label] = history.history['val_' + label]\n",
    "    print(history.history)\n",
    "    # loss_train_list.append(data['loss'])\n",
    "    # loss_test_list.append(data['val_loss'])\n",
    "    # acc_train_list.append(data['accuracy'])\n",
    "    # acc_test_list.append(data['val accuracy'])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n",
     "is_executing": true
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "outputs": [],
   "source": [
    "\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}